package csc.traning.wpsj.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.User;
import csc.traning.wpsj.dao.UserDB;

/**
 * Servlet implementation class Profile_Editer
 */
public class Profile_Editor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Profile_Editor() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		if (u == null) {
			response.sendRedirect("logon.jsp");
		}
		String newUsername = request.getParameter("userName");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String cellPhone = request.getParameter("cellphone");
		String email = request.getParameter("emailAddress");
		List<String> messages = new ArrayList<String>();
		
		if ("".equals(newUsername)) {
			messages.add("Username is required");
		}
		if ("".equals(firstName)) {
			messages.add("Firstname is required");
		}
		if ("".equals(lastName)) {
			messages.add("Lastname is required");
		}
		if ("".equals(email)) {
			messages.add("Email is required");
		}
		if (messages.size() > 0) {
			request.setAttribute("messages", messages);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("profile_editor.jsp");
			dispatcher.forward(request, response);
		} else {
			try {
				if (u != null) {
					UserDB.updateUserInfo(u.getUserName(), newUsername,
							firstName, lastName, cellPhone, email);
					session.setAttribute("user", u);
					messages.add("Update user info successfully");
					request.setAttribute("messages", messages);
					RequestDispatcher dispatcher = request
							.getRequestDispatcher("profile_editor.jsp");
					dispatcher.forward(request, response);
				}

			} catch (Exception e1) {
				throw new ServletException(e1.getMessage());
			}
		}
	}
}
